//
//  ResetPasswordViewController.m
//  SoundPill
//
//  Created by 温冬 on 15/5/1.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "ResetPasswordViewController.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
@interface ResetPasswordViewController ()

@end

@implementation ResetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.reset = [[Reset alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:self.reset];
    self.reset.securityCode.delegate = self;
    self.reset.password.field.delegate = self;
    [self.reset.close addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.reset.certain addTarget:self action:@selector(certain:) forControlEvents:UIControlEventTouchUpInside];
    [self.reset.timeButton addTarget:self action:@selector(timeButton:) forControlEvents:UIControlEventTouchUpInside];
    [self createCountDown];
}

- (void)close:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)certain:(UIButton *)button
{
    if (self.reset.securityCode.text.length == 0) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"验证码不能为空";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码不能为空" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:0.5];
        
    }else if (self.reset.password.field.text.length < 6){
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"密码格式不正确，至少6位" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:0.5];
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"密码格式不正确，至少6位";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }else{
        [self uploading];
    }
}

- (void)dismissAlert:(UIAlertView *)alertView
{
    if (alertView) {
        [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES];
    }
}

- (void)timeButton:(UIButton *)button
{
    [self createCountDown];
    [self requsetSecurityCode];
}


#pragma mark - 上传用户新密码到服务器
- (void)uploading
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/reset"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.reset.telNumber, @"mobile", self.reset.password.field.text, @"password", self.reset.securityCode.text, @"code", nil];
//    NSLog(@"dic = %@", dic);
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"重置密码成功";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"验证码不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
        
    }];
}

#pragma mark - 验证码倒计时
- (void)createCountDown
{
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.reset.timeLabel.hidden = YES;
                [self.reset.timeButton setTitle:@"重新获取" forState:UIControlStateNormal];
                self.reset.timeButton.hidden = NO;
                self.reset.timeButton.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.reset.timeLabel.hidden = NO;
                self.reset.timeLabel.text = [NSString stringWithFormat:@"剩余%@秒",strTime];
                self.reset.timeLabel.textAlignment = NSTextAlignmentCenter;
                self.reset.timeButton.hidden = YES;
                self.reset.timeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 请求云片发送验证码
- (void)requsetSecurityCode
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/sendsms?mobile=%@&type=reset",self.reset.telNumber];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [netWorkManager stopMonitoring];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 点击完成按钮 - 提交新密码
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (self.reset.securityCode.text.length == 0) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"验证码不能为空";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码不能为空" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:0.5];
        
    }else if (self.reset.password.field.text.length < 6){
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"密码格式不正确，至少6位" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:0.5];
        
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"密码格式不正确, 至少6位";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }else{
        [self uploading];
    }
    return YES;
}

#pragma mark - 回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.reset.securityCode resignFirstResponder];
    [self.reset.password.field resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
